package com.android.vestel.photoroid;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.util.Log;


public class FlickrClient extends WebPhotos{
	private static String API_KEY = "2f47a8b8f51442d4e57ef734c9b1f2f0";	
	private static String USER_ID="";
	private static String METHOD_GETALLPHOTOS = "flickr.photos.search";	
	private static String USERID_REQUEST="http://api.flickr.com/services/rest/";	
	private static ArrayList<String> PHOTO_LIST = new ArrayList<String>();
	private static ArrayList<String> PHOTO_ID_LIST = new ArrayList<String>();
	private HashMap<String,String> images = new HashMap<String,String>();
	String TAG = "FlickrClient";
	
//	FlickrClient(String IdOfUser) throws HttpException, IOException, SAXException, ParserConfigurationException{
//		USER_ID=IdOfUser;
//		XMLParsing();
//	}

	FlickrClient(String NameOfUser) {
		FlickrUserId UID = new FlickrUserId(NameOfUser);
		Log.e(TAG,"FlikcrConstructor");
		try {
			USER_ID=UID.getUserId();
			Log.e(TAG,"FlikcrConstructor userid = "+USER_ID);
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public HashMap<String,String> getImages(){
		 return images;
	 }
	
	public void getAllImages() {
		
		try {
			PostMethod pmethodPhoto = new PostMethod(USERID_REQUEST);
			
			pmethodPhoto.addParameter("method", METHOD_GETALLPHOTOS);
			pmethodPhoto.addParameter("api_key", API_KEY);
			pmethodPhoto.addParameter("user_id", USER_ID);
			pmethodPhoto.addParameter("privacy_filter","1");//1 yani public fotolar
			
			
			HttpClient clientPhoto = new HttpClient();
			
			int statusCodePhoto = clientPhoto.executeMethod(pmethodPhoto);
			
			if (statusCodePhoto != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + pmethodPhoto.getStatusLine());
			}
			InputStream rstreamPhoto = null;
			
			// Get the response body
			rstreamPhoto = pmethodPhoto.getResponseBodyAsStream();
			
			Document responsePhoto = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rstreamPhoto);
			
			NodeList rotateResponseListPhoto =responsePhoto.getElementsByTagName("photo");
			
			String urlName="";
			String tempImageID;
			
			for(int i =0 ; i < rotateResponseListPhoto.getLength() ; i++){
				urlName+="http://farm";
				urlName+=rotateResponseListPhoto.item(i).getAttributes().getNamedItem("farm").getNodeValue();
				urlName+=".static.flickr.com/";
				urlName+=rotateResponseListPhoto.item(i).getAttributes().getNamedItem("server").getNodeValue();
				urlName+="/"+rotateResponseListPhoto.item(i).getAttributes().getNamedItem("id").getNodeValue();
				urlName+="_"+rotateResponseListPhoto.item(i).getAttributes().getNamedItem("secret").getNodeValue();
				urlName+="_b.jpg";
				PHOTO_LIST.add(urlName);
				tempImageID = rotateResponseListPhoto.item(i).getAttributes().getNamedItem("id").getNodeValue();
				PHOTO_ID_LIST.add(tempImageID);
				images.put(tempImageID, urlName);
				urlName="";
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (DOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
	}
	public boolean is_valid(){
		if(USER_ID == null){
			return false;
		}
		else {
			return true;
		}
	}
	
	public ArrayList<String> getImagePaths(){
		return PHOTO_LIST;
	}
	
	
	private class FlickrUserId {
		private static final String API_KEY = "2f47a8b8f51442d4e57ef734c9b1f2f0";
		private String USERNAME;
		private String USER_ID;
		private static final String METHOD_GETUSERID = "flickr.people.findByUsername";
		private static final String USERID_REQUEST="http://api.flickr.com/services/rest/";
		
		FlickrUserId(String nameOfUser){
			USERNAME = nameOfUser;
			
		}
		
		private void findUserId() {
			try {
				Log.e(TAG,"FlikcrUserId findUserId method");
				PostMethod pmethod = new PostMethod(USERID_REQUEST);
				
				pmethod.addParameter("method", METHOD_GETUSERID);
				pmethod.addParameter("api_key", API_KEY);
				pmethod.addParameter("username", USERNAME);
				
				
				HttpClient client = new HttpClient();
				
				int statusCode = client.executeMethod(pmethod);
				
				if (statusCode != HttpStatus.SC_OK) {
					System.err.println("Method failed: " + pmethod.getStatusLine());
				}
				
				InputStream rstream = null;
				
				rstream = pmethod.getResponseBodyAsStream();
				
				Document response = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(rstream);
				
				Node userIdResponse = response.getElementsByTagName("user").item(0).getAttributes().getNamedItem("id");
				
				if (userIdResponse != null) {
					USER_ID = userIdResponse.getTextContent();
				} 
				else {
					Log.e(TAG,"an error occured while getting user id");
					USER_ID = null;
				}
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (HttpException e) {
				e.printStackTrace();
			} catch (DOMException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			}
	        
		}
		
		public String getUserId() throws HttpException, IOException, SAXException, ParserConfigurationException{
			findUserId();
			return USER_ID;
		}
		

	}

	@Override
	public ArrayList<String> getImageIDs() {
		return PHOTO_ID_LIST;
	}
	
}

